<script setup name="Role">
import {addRole, changeRoleStatus, delRole, getRole, listRole, updateRole} from "@/api/hrp/role";
import {roleMenuTreeselect, treeselect as menuTreeselect} from "@/api/sys/menu";
import {getCurrentInstance, nextTick, reactive} from "vue";
import {useRouter} from "vue-router";

const router = useRouter();
const {proxy} = getCurrentInstance();
const {sys_is, hrp_role_key} = proxy.useDict("sys_is", "hrp_role_key");
const menuRef = ref(null);
const authRef = ref(null);

const pd = reactive({
  roleList: [],
  open: false,
  loading: true,
  showSearch: true,
  ids:[],
  single:true,
  multiple:true,
  total:0,
  title:"",
  dateRange:[],
  menuOptions:[],
  authOptions:[],
  menuExpand:true,
  authExpand:true,
  menuNodeAll:false,
  authNodeAll:false,
  menuCheckStrictly: true,
  authCheckStrictly: true,
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    roleName: undefined,
    roleKey: undefined,
    status: undefined
  },
  rules: {
    roleName: [{required: true, message: "角色名称不能为空", trigger: "blur"}],
    roleKey: [{required: true, message: "权限字符不能为空", trigger: "blur"}],
    roleSort: [{required: true, message: "角色顺序不能为空", trigger: "blur"}]
  },
});

/** 查询角色列表 */
function getList() {
  pd.loading = true;
  listRole(proxy.addDateRange(pd.queryParams, pd.dateRange)).then(response => {
    pd.roleList = response.rows;
    pd.total = response.total;
    pd.loading = false;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  pd.dateRange = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  const roleIds = row.roleId || pd.ids;
  proxy.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?').then(function () {
    return delRole(roleIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...pd.queryParams,
  }, `role_${new Date().getTime()}.xlsx`);
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  pd.ids = selection.map(item => item.roleId);
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?').then(function () {
    return changeRoleStatus(row.roleId, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
}

/** 分配用户 */
function handleRoleUser(row) {
  router.push("/sys/role-auth/user/" + row.roleId);
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then(response => {
    pd.menuOptions = response.menus;
    pd.authOptions = response.auths;
  });
}
/** 重置新增的表单以及其他数据  */
function reset() {
  if (menuRef.value != undefined) {
    menuRef.value.setCheckedKeys([]);
    authRef.value.setCheckedKeys([]);
  }
  pd.menuExpand = true;
  pd.authExpand = true;
  pd.authNodeAll = false;
  pd.menuNodeAll = false;
  pd.menuCheckStrictly= true;
  pd.authCheckStrictly= true;
  pd.form = {
    roleId: undefined,
    roleName: undefined,
    roleKey: undefined,
    roleSort: 0,
    status: "0",
    menuIds: [],
    authIds: [],
    remark: undefined
  };
  proxy.resetForm("roleRef");
}

/** 添加角色 */
function handleAdd() {
  reset();
  getMenuTreeselect();
  pd.open = true;
  pd.title = "添加角色";
}

/** 修改角色 */
function handleUpdate(row) {
  reset();
  const roleId = row.roleId || pd.ids;
  const roleMenu = getRoleMenuTreeselect(roleId);
  getRole(roleId).then(response => {
    pd.form = response.data;
    pd.form.roleSort = Number(pd.form.roleSort);
    pd.open = true;
    nextTick(() => {
      roleMenu.then((res) => {
        let checkedKeys = res.checkedKeys;
        checkedKeys.forEach((v) => {
          nextTick(() => {
            menuRef.value.setChecked(v, true, false);
            authRef.value.setChecked(v, true, false);
          });
        });
      });
    });
    pd.title = "修改角色";
  });
}

/** 根据角色ID查询菜单树结构 */
function getRoleMenuTreeselect(roleId) {
  return roleMenuTreeselect(roleId).then(response => {
    pd.menuOptions = response.menus;
    pd.authOptions = response.auths;
    return response;
  });
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  if (type == "menu") {
    let treeList = pd.menuOptions;
    for (let i = 0; i < treeList.length; i++) {
      menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  } else if (type == "auth") {
    let treeList = pd.authOptions;
    for (let i = 0; i < treeList.length; i++) {
      authRef.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  if (type == "menu") {
    menuRef.value.setCheckedNodes(value ? pd.menuOptions : []);
  } else if (type == "auth") {
    authRef.value.setCheckedNodes(value ? pd.authOptions : []);
  }
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  if (type == "menu") {
    pd.menuCheckStrictly = value ? true : false;
  } else if (type == "auth") {
    pd.authCheckStrictly = value ? true : false;
  }
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let menusCheckedKeys = menuRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let menusHalfCheckedKeys = menuRef.value.getHalfCheckedKeys();
  menusCheckedKeys.unshift.apply(menusCheckedKeys, menusHalfCheckedKeys);

  // 目前被选中的菜单节点
  let authsCheckedKeys = authRef.value.getCheckedKeys();
  menusCheckedKeys.unshift.apply(menusCheckedKeys, authsCheckedKeys);
  // 半选中的菜单节点
  let authsHalfCheckedKeys = authRef.value.getHalfCheckedKeys();
  menusCheckedKeys.unshift.apply(menusCheckedKeys, authsHalfCheckedKeys);
  return menusCheckedKeys;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (pd.form.roleId != undefined) {
        pd.form.menuIds = getMenuAllCheckedKeys();
        updateRole(pd.form).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          pd.open = false;
          getList();
        });
      } else {
        pd.form.menuIds = getMenuAllCheckedKeys();
        addRole(pd.form).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          pd.open = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  pd.open = false;
  reset();
}

getList();
</script>


<template>
  <div class="app-container">
    <el-form :model="pd.queryParams" ref="queryRef" v-show="pd.showSearch" :inline="true" label-width="68px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="pd.queryParams.roleName" placeholder="请输入角色名称" clearable style="width: 120px"
                  @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <DictSelect :list="hrp_role_key" placeholder="请输入权限字符" v-model:code="pd.queryParams.roleKey"/>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 280px">
        <el-date-picker v-model="pd.dateRange" value-format="YYYY-MM-DD" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['sys:role:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate"
                   v-hasPermi="['sys:role:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete"
                   v-hasPermi="['sys:role:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['sys:role:export']">导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="pd.loading" :data="pd.roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="角色编号" prop="roleId" width="120"/>
      <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true" width="150">
        <template #default="scope">
          <dict-tag :options="hrp_role_key" :value="scope.row.roleKey"/>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" prop="roleSort" width="100"/>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                     @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="修改" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['sys:role:edit']"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['sys:role:remove']"></el-button>
          </el-tooltip>
          <!--          <el-tooltip content="数据权限" placement="top" v-if="scope.row.roleId !== 1">-->
          <!--            <el-button link type="primary" icon="CircleCheck" @click="handleDataScope(scope.row)"-->
          <!--                       v-hasPermi="['sys:role:edit']"></el-button>-->
          <!--          </el-tooltip>-->
          <el-tooltip content="分配用户" placement="top" v-if="scope.row.roleId !== 1">
            <el-button link type="primary" icon="User" @click="handleRoleUser(scope.row)"
                       v-hasPermi="['sys:role:edit']"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="pd.total > 0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                v-model:limit="pd.queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="pd.title" v-model="pd.open" width="980" append-to-body>
      <el-form ref="roleRef" :model="pd.form" :rules="pd.rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="pd.form.roleName" placeholder="请输入角色名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="roleKey">
              <template #label>
                  <span>
                     <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)。在其他选择人群中也有使用到" placement="top">
                        <el-icon><question-filled/></el-icon>
                     </el-tooltip>
                     权限字符
                  </span>
              </template>
              <DictSelect :list="hrp_role_key" v-model:code="pd.form.roleKey"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="角色顺序" prop="roleSort">
              <el-input-number v-model="pd.form.roleSort" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="菜单分发">
              <el-checkbox v-model="pd.menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
              <el-checkbox v-model="pd.menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选
              </el-checkbox>
              <el-checkbox v-model="pd.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动
              </el-checkbox>
              <el-tree class="tree-border" :data="pd.menuOptions" show-checkbox
                       ref="menuRef" node-key="id" :check-strictly="!pd.menuCheckStrictly"
                       empty-text="加载中，请稍候" :props="{ label: 'label', children: 'children' }"></el-tree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限分发">
              <el-checkbox v-model="pd.authExpand" @change="handleCheckedTreeExpand($event, 'auth')">展开/折叠</el-checkbox>
              <el-checkbox v-model="pd.authNodeAll" @change="handleCheckedTreeNodeAll($event, 'auth')">全选/全不选
              </el-checkbox>
              <el-checkbox v-model="pd.authCheckStrictly" @change="handleCheckedTreeConnect($event, 'auth')">父子联动
              </el-checkbox>
              <el-tree class="tree-border" :data="pd.authOptions" show-checkbox
                       ref="authRef" node-key="id" :check-strictly="!pd.authCheckStrictly"
                       empty-text="加载中，请稍候" :props="{ label: 'label', children: 'children' }"></el-tree>
            </el-form-item>

          </el-col>

        </el-row>
        <el-form-item label="备注">
          <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
